package filereaders;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


/**
 * Can parse basic xml files such as example.xml.
 * 
 * @author Paul Dannenberg
 * 
 */
public class XmlParser extends Parser {
    
    private static final String XML_FORMAT = "#text";
    private File myFile;
    private Document myDocument;


    
    /**
     * Creates an object that will attempt to parse
     * the specified file.
     * @param file
     */
    public XmlParser(File file) {
        super(file);
        myFile = file;
    }

    private void createDocument() {
        if (myDocument == null) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            try {
                myDocument = factory.newDocumentBuilder().parse(myFile);
            } 
            catch (ParserConfigurationException e) {
                e.printStackTrace();
            }
            catch (SAXException e) {
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
   
    private NodeList findData(String fieldName) {
        createDocument();
        Element docEle = myDocument.getDocumentElement();
        NodeList nodeList = docEle.getElementsByTagName(fieldName);
        return nodeList;
    }

    private String parseDocument (String fieldName) {
        NodeList nodeList = findData(fieldName);
        Node nodeData = null;
        if (nodeList != null && nodeList.getLength() > 0) {
            Element dataElement = (Element) nodeList.item(0);
            nodeData = dataElement.getFirstChild();
        }
        return nodeData.getNodeValue();
    }

    @Override
    protected List<String> readSector(int indexOfData) {
        String fieldName = getOptions().get(indexOfData);
        String parsedData = parseDocument(fieldName);
        return Arrays.asList(parsedData.split(" "));
    }

    @Override
    public List<String> getOptions() {
        createDocument();
        List<String> options = new ArrayList<String>();
        Element docEle = myDocument.getDocumentElement();
        NodeList nodes = docEle.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            if (!XML_FORMAT.equals(nodes.item(i).getNodeName())) {
                options.add(nodes.item(i).getNodeName());
            }
        }
        return options;
    }  
}
